<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class Mailer {

	private $creator; 
	private $alerter;
	private $db_access;

	public function __construct() {
		$this->creator = new FormCreator();
		$this->alerter = new Alerter();
		$this->db_access = new DbAccessor();
	}

	public function set_alerter($alerter) {
		$this->alerter = $alerter;
	}

	public function mail_form($contents=array()) {
		$inputs = array();
		
		$inputs[] = $this->creator->input_text("Bericht", "body", $contents['body']);
		$inputs[] = $this->creator->input_field("Onderwerp", "subject", $contents['subject']);
		$inputs[] = $this->creator->input_field("CC:", "cc", $contents['cc']);
		$inputs[] = $this->creator->input_field("Aan:", "to", $contents['to']);
		$inputs[] = $this->creator->header("Een intern bericht sturen");
		
		$inputs[] = $this->creator->input_hidden("mailing", "1");
		
		return $this->creator->create("mailform", $inputs, "/service/.mailbox");
	}

	public function fetch_alerts($page) { //TODO: move to Alerter
		$alerts = $this->db_access->db_do_query($this->db_access->db_query_select(array(array("*")), array("ALERT"), "user_id = {$_SESSION['user_id']}"));
		if ($this->db_access->db_num_rows($alerts) > 0)
			while ($a = $this->db_access->db_fetch_array($alerts))
				$this->alerter->add_alert($a['alert'], '', 0, $a['alert_id']);
	}

	public function fetch_mail($page) {
		$mails = ($this->db_access->db_do_query($this->db_access->db_query_select(array(array(), "MAIL_HEADER.*"), 
						 array("MAIL_HEADER INNER JOIN MAIL_TO ON MAIL_HEADER.mail_id = MAIL_TO.mail_id", "DUMMY"),
							   "MAIL_TO.user_id = {$_SESSION['user_id']} AND sent > '{$_SESSION['member']['last_visit']}' 
							    AND !MAIL_TO.hasread AND !MAIL_TO.trashed AND !MAIL_TO.deleted", "sent DESC")));
		if ($this->db_access->db_num_rows($mails) > 0) {
			$m = $this->db_access->db_fetch_array($mails);
			$this->alerter->add_alert("Nieuw intern bericht !! [<a href=/service/.mailbox>mailbox</a>] - [<a href=/service/{$m[mail_id]}.mail>bericht</a>]");
		}
	}
	
}

?>
